<template>
    <form>
        <h1>修改图书</h1>
        <table>
            <tr>
                <td>图书名称：</td>
                <td><input type="text" v-model="book.bookName" /></td>
            </tr>

            <tr>
                <td>作者：</td>
                <td><input type="text" v-model="book.autor" /></td>
            </tr>

            <tr>
                <td>价格：</td>
                <td><input type="text" v-model="book.price" /></td>
            </tr>

            <tr>
                <td colspan="2">
                    <input type="button" value="保存" @click="save" />
                    <input type="button" value="取消" @click="$router.push('/')" />
                </td>
            </tr>
        </table>
    </form>
</template>

<script setup>
import { ref, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import axios from "axios"

const router = useRouter()
const route = useRoute()

// 后端 api
const api = "http://localhost:8000/books"

// 图书信息
const book = ref({
    bookName: '',
    autor: '',
    price: ''
})

// 修改
async function save() {
    for (const key in book.value) {
        if (book.value[key] === '') {
            return
        }
    }

    const id = route.params.id

    const data = await axios.put(`${api}/${id}`, book.value)
    if (data.data.code === 200) {
        router.push("/")
    }
}

// 生命周期方法
onMounted(async () => {
    const data = await axios.get(`${api}/${route.params.id}`)
    book.value = data.data.data
})
</script>